package com.sc.VenusQueryBeta.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.provider.Settings;
import android.support.v4.content.LocalBroadcastManager;
import android.text.TextUtils;
import android.util.Log;

import com.hengjun.kingstar.sdk.rxbus.RxBus;
import com.hengjun.kingstar.sdk.utils.LogUtil;
import com.hengjun.kingstar.sdk.utils.LogUtils;
import com.hengjun.kingstar.sdk.utils.SpUtils;
import com.sc.VenusQueryBeta.constant.Constants;
import com.sc.VenusQueryBeta.constant.event.PusMsgEvent;
import com.sc.VenusQueryBeta.global.MyApplication;
import com.sc.VenusQueryBeta.model.bean.login.UsersLoginBean;
import com.sc.VenusQueryBeta.model.sqlite.DataBaseDao;
import com.sc.VenusQueryBeta.ui.activites.MainActivity;
import com.sc.VenusQueryBeta.ui.activites.MsgActivity;
import com.sc.VenusQueryBeta.ui.widgets.ExampleUtil;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Iterator;

import cn.jpush.android.api.JPushInterface;


/**
 * 自定义接收器
 * <p>
 * 如果不定义这个 Receiver，则：
 * 1) 默认用户会打开主界面
 * 2) 接收不到自定义消息
 */
public class MyReceiver extends BroadcastReceiver {
    private static final String TAG = "JIGUANG-Example";
    private String word;
    private DataBaseDao dataBaseDao;
    private UsersLoginBean loginBean;

    @Override
    public void onReceive(final Context context, Intent intent) {
        try {
            Bundle bundle = intent.getExtras();
            Log.d(TAG, "[MyReceiver] onReceive - " + intent.getAction() + ", extras: " + printBundle(bundle));
            LogUtil.e("smsddd=" + JPushInterface.ACTION_NOTIFICATION_OPENED);
            if (JPushInterface.ACTION_REGISTRATION_ID.equals(intent.getAction())) {
                String regId = bundle.getString(JPushInterface.EXTRA_REGISTRATION_ID);
                Log.d(TAG, "[MyReceiver] 接收Registration Id : " + regId);
                //send the Registration Id to your server...

            } else if (JPushInterface.ACTION_MESSAGE_RECEIVED.equals(intent.getAction())) {
                Log.d(TAG, "[MyReceiver] 接收到推送下来的自定义消息: " + bundle.getString(JPushInterface.EXTRA_MESSAGE));
                processCustomMessage(context, bundle);

            } else if (JPushInterface.ACTION_NOTIFICATION_RECEIVED.equals(intent.getAction())) {//"[MyReceiver] 接收到推送下来的通知");
                Log.d(TAG, "[MyReceiver] 接收到推送下来的通知");
                Bundle bundle2 = intent.getExtras();
                StringBuilder sb = new StringBuilder();
                for (String key : bundle2.keySet()) {
                    if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                        if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                            Log.i(TAG, "This message has no Extra data");
                            continue;
                        }

                        try {
                            JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                            Iterator<String> it = json.keys();

                            while (it.hasNext()) {
                                String myKey = it.next();
                                sb.append("\nkey:" + key + ", value: [" +
                                        myKey + "" + json.optString(myKey) + "]");
                                word = json.optString(myKey).substring(0, 1);
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, "Get message extra JSON error!");
                        }

                    } else {
                        sb.append("\nkey:" + key + ", value:" + bundle.get(key));
                    }
                }

                if (word.equals("2")) {//是异地通知
                    loginBean = SpUtils.getObject(MyApplication.app, UsersLoginBean.class);
                    final int notifactionId0 = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                    Log.d(TAG, "[MyReceiver] 接收到推送下来的通知的ID: " + notifactionId0);
                    SpUtils.putInt(MyApplication.app, Constants.NOTIFICATION_ID, notifactionId0);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (!Settings.canDrawOverlays(context)) {
                            //没有悬浮窗权限,跳转直接
                            if (MyApplication.isBackground(context)) {//在后台

                            } else {
                                LogUtil.e("/没有悬浮窗权限,跳转直接");
//                                SpUtils.clear(MyApplication.app);
                                LogUtil.e("565656565=" + loginBean.getId());
                                SpUtils.putBoolean(MyApplication.app, Constants.OUT_DATE, true);
                                SpUtils.putString(MyApplication.app, Constants.PHONE, loginBean.getId());
                                SpUtils.putString(MyApplication.app, Constants.AREADECODE, loginBean.getAreaCode());
                                SpUtils.putBoolean(MyApplication.app, Constants.DISTANCE_OUT, true);//保存异地 标志
                                int anInt1 = SpUtils.getInt(MyApplication.app, Constants.UNREAD_NUM, 0);
                                SpUtils.putInt(MyApplication.app, Constants.UNREAD_NUM, anInt1);
                                Intent intent2 = new Intent(context, MainActivity.class);
                                intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                                SpUtils.putInt(MyApplication.app, Constants.NOTIFICATION_ID, notifactionId0);
                                context.startActivity(intent2);
                            }
//                            JPushInterface.clearNotificationById(MyApplication.app,notifactionId);
                        } else {
                            LogUtil.e("有悬浮窗权限");
//                            SpUtils.clear(MyApplication.app);
                            LogUtil.e("565656565=" + loginBean.getId());
                            SpUtils.putBoolean(MyApplication.app, Constants.OUT_DATE, true);
                            SpUtils.putString(MyApplication.app, Constants.PHONE, loginBean.getId());
                            SpUtils.putString(MyApplication.app, Constants.AREADECODE, loginBean.getAreaCode());
                            SpUtils.putBoolean(MyApplication.app, Constants.DISTANCE_OUT, true);//保存异地 标志
                            int anInt1 = SpUtils.getInt(MyApplication.app, Constants.UNREAD_NUM, 0);
                            SpUtils.putInt(MyApplication.app, Constants.UNREAD_NUM, anInt1);
                            Intent intent1 = new Intent(context, MainActivity.class);
                            SpUtils.putInt(MyApplication.app, Constants.NOTIFICATION_ID, notifactionId0);
//                            intent1.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                            context.startActivity(intent1);
//                            SpUtils.clear(MyApplication.app);
//                            LogUtil.e("is distance 2");
//                            AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(context);
//                            dialogBuilder.setTitle("VGS查数提示");
//                            dialogBuilder.setMessage("你的VGS查数账号正在异地登录！");
//                            dialogBuilder.setCancelable(false);
//                            dialogBuilder.setIcon(R.drawable.logo_login);
//                            dialogBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
//                                @Override
//                                public void onClick(DialogInterface dialogInterface, int i) {
//                                    JPushInterface.removeLocalNotification(MyApplication.app,notifactionId);
//                                    SpUtils.clear(MyApplication.app);
//                                    SpUtils.putBoolean(MyApplication.app, Constants.DISTANCE_OUT, true);//保存异地 标志
//                                    Intent intent = new Intent(context, MainActivity.class);
//                                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
//                                    context.startActivity(intent);
//                                    JPushInterface.clearNotificationById(MyApplication.app,notifactionId);
//
//                                }
//                            });
//                            AlertDialog alertDialog = dialogBuilder.create();
//                            alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
//                            alertDialog.show();
                        }
                    }

                } else {//收到的是信息通知
                    LogUtil.e("not 2");

                    int unreadNum = SpUtils.getInt(MyApplication.app, Constants.UNREAD_NUM, 0);
                    SpUtils.putInt(MyApplication.app, Constants.UNREAD_NUM, unreadNum + 1);
//                    new Handler().postDelayed(new Runnable(){
//                        public void run() {
                    //execute the task
                    RxBus.getInstance().post(new PusMsgEvent());//通知msg
//                    RxBus.getInstance().post(new PusReadNumEvent("open"));//通知红点
                    Intent intentx = new Intent("com.nyl.orderlybroadcast.AnotherBroadcastReceiver");
                    //发送本地广播
                    LocalBroadcastManager.getInstance(context).sendBroadcastSync(intentx);
//                    Intent intentx = new Intent("com.insert.to.db");
////                            //发送本地广播
//                    context.sendBroadcast(intentx);
                    if (MyApplication.isBackground(context)) {//在后台收到信息
                        SpUtils.putBoolean(MyApplication.app, Constants.MSG_BACkGROUND, true);
                        SpUtils.putBoolean(MyApplication.app, Constants.MSG_BACkGROUND1, true);
                    }

                }
//                    }, 3000);
//                }

            } else if (JPushInterface.ACTION_NOTIFICATION_OPENED.equals(intent.getAction())) {
                Log.d(TAG, "[MyReceiver] 用户点击打开了通知");
                LogUtil.e("smsddd00=" + JPushInterface.ACTION_NOTIFICATION_OPENED);
                Bundle bundle1 = intent.getExtras();
                StringBuilder sb = new StringBuilder();
                for (String key : bundle1.keySet()) {
                    if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                        if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                            Log.i(TAG, "This message has no Extra data");
                            continue;
                        }

                        try {
                            JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                            Iterator<String> it = json.keys();

                            while (it.hasNext()) {
                                String myKey = it.next();
                                sb.append("\nkey:" + key + ", value: [" +
                                        myKey + "" + json.optString(myKey) + "]");
                                word = json.optString(myKey).substring(0, 1);
                            }
                        } catch (JSONException e) {
                            Log.e(TAG, "Get message extra JSON error!");
                        }

                    } else {
                        sb.append("\nkey:" + key + ", value:" + bundle.get(key));
                    }
                }
                if (word.equals("2")) {
                    final int notifactionId1 = bundle.getInt(JPushInterface.EXTRA_NOTIFICATION_ID);
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
                        if (!Settings.canDrawOverlays(context)) {
                            //没有悬浮窗权限,跳转申请 因为已经跳转过了
//                            SpUtils.putBoolean(MyApplication.app, Constants.INFORM, true);
//                            SpUtils.clear(MyApplication.app);
                            LogUtils.e("565656565=" + loginBean.getId());
                            SpUtils.putBoolean(MyApplication.app, Constants.OUT_DATE, true);
                            SpUtils.putString(MyApplication.app, Constants.PHONE, loginBean.getId());
                            SpUtils.putString(MyApplication.app, Constants.AREADECODE, loginBean.getAreaCode());
                            SpUtils.putInt(MyApplication.app, Constants.NOTIFICATION_ID, notifactionId1);
                            SpUtils.putBoolean(MyApplication.app, Constants.DISTANCE_OUT, true);//保存异地 标志
                            int anInt1 = SpUtils.getInt(MyApplication.app, Constants.UNREAD_NUM, 0);
                            SpUtils.putInt(MyApplication.app, Constants.UNREAD_NUM, anInt1);
                            LogUtil.e("word=========" + word);
                            LogUtil.e("点击进异地登录" + word);
                            Intent i = new Intent(context, MainActivity.class);
                            //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                            context.startActivity(i);
                        } else {
                            LogUtil.e("有悬浮");
                        }
                    }
                } else {
                    LogUtil.e("点击通知进=========" + word);
                    SpUtils.putBoolean(MyApplication.app, Constants.ISNOTIFICATION, true);
                    //打开自定义的Activity
                    Intent i = new Intent(context, MainActivity.class);
//                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);

//                    i.putExtras(bundle);
                    //i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    context.startActivity(i);
                }
            } else if (JPushInterface.ACTION_RICHPUSH_CALLBACK.equals(intent.getAction())) {
                Log.d(TAG, "[MyReceiver] 用户收到到RICH PUSH CALLBACK: " + bundle.getString(JPushInterface.EXTRA_EXTRA));
                //在这里根据 JPushInterface.EXTRA_EXTRA 的内容处理代码，比如打开新的Activity， 打开一个网页等..

            } else if (JPushInterface.ACTION_CONNECTION_CHANGE.equals(intent.getAction())) {
                boolean connected = intent.getBooleanExtra(JPushInterface.EXTRA_CONNECTION_CHANGE, false);
                Log.w(TAG, "[MyReceiver]" + intent.getAction() + " connected state change to " + connected);
            } else {
                Log.d(TAG, "[MyReceiver] Unhandled intent - " + intent.getAction());
            }
        } catch (Exception e) {

        }

    }

    // 打印所有的 intent extra 数据
    private static String printBundle(Bundle bundle) {
        StringBuilder sb = new StringBuilder();
        for (String key : bundle.keySet()) {
            if (key.equals(JPushInterface.EXTRA_NOTIFICATION_ID)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getInt(key));
            } else if (key.equals(JPushInterface.EXTRA_CONNECTION_CHANGE)) {
                sb.append("\nkey:" + key + ", value:" + bundle.getBoolean(key));
            } else if (key.equals(JPushInterface.EXTRA_EXTRA)) {
                if (TextUtils.isEmpty(bundle.getString(JPushInterface.EXTRA_EXTRA))) {
                    Log.i(TAG, "This message has no Extra data");
                    continue;
                }

                try {
                    JSONObject json = new JSONObject(bundle.getString(JPushInterface.EXTRA_EXTRA));
                    Iterator<String> it = json.keys();

                    while (it.hasNext()) {
                        String myKey = it.next();
                        sb.append("\nkey:" + key + ", value: [" +
                                myKey + "" + json.optString(myKey) + "]");
                        LogUtil.e("json.optString(myKey)==========");
                    }

                    LogUtil.e("json.optString(myKey)==========" + json.optString(it.toString()));

                } catch (JSONException e) {
                    Log.e(TAG, "Get message extra JSON error!");
                }

            } else {
                sb.append("\nkey:" + key + ", value:" + bundle.get(key));
            }
        }
        return sb.toString();
    }

    //send msg to MainActivity
    private void processCustomMessage(Context context, Bundle bundle) {
        if (MsgActivity.isForeground) {
            String message = bundle.getString(JPushInterface.EXTRA_MESSAGE);
            String extras = bundle.getString(JPushInterface.EXTRA_EXTRA);
            Intent msgIntent = new Intent(MsgActivity.MESSAGE_RECEIVED_ACTION);
            msgIntent.putExtra(MsgActivity.KEY_MESSAGE, message);
            if (!ExampleUtil.isEmpty(extras)) {
                try {
                    JSONObject extraJson = new JSONObject(extras);
                    if (extraJson.length() > 0) {
                        msgIntent.putExtra(MsgActivity.KEY_EXTRAS, extras);
                    }
                } catch (JSONException e) {

                }

            }
            LocalBroadcastManager.getInstance(context).sendBroadcast(msgIntent);
        }
    }
}
